/*
 * AddressModel.java
 * business
 *
 * Created by ChenTao on 2017/3/2.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.data.model;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.yidiandao.business.constant.Urls;
import com.yidiandao.business.data.address.Area;
import com.yidiandao.business.data.bean.UserAddress;
import com.yidiandao.business.data.event.RefreshAddressListStateEvent;
import com.yidiandao.business.data.net.BaseRequest;
import com.yidiandao.business.data.net.BaseResponse;
import com.yidiandao.business.data.net.NetBiz;
import com.yidiandao.business.data.net.NetListener;
import com.yidiandao.business.data.net.exception.BizErrorInfo;
import com.yidiandao.business.data.net.exception.NetErrorInfo;
import com.yidiandao.business.data.request.AddressRequest;
import com.yidiandao.business.data.request.ChangeAddressRequest;
import com.yidiandao.business.data.request.DeleteUserAddressRequest;
import com.yidiandao.business.data.request.QueryAreaRequest;
import com.yidiandao.business.data.request.SetDefaultAddressRequest;
import com.yidiandao.business.data.request.UpdateAddressRequest;
import com.yidiandao.business.data.response.AddressResponse;
import com.yidiandao.business.data.response.QueryAreaResponse;
import com.yidiandao.business.data.response.QueryUserAddressListResponse;
import com.yidiandao.business.manager.UserAddressManager;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.listview.Functional;
import com.yidiandao.business.ui.widget.listview.displaylistitem.AddAddressListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.AddressManagerListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ChooseAddressAddListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ChooseAddressListItem;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户收货地址的Model
 */
public class AddressModel implements IAddressModel {

    private NetBiz mNetBiz = new NetBiz();

    private List<DisplayListItem> mChooseDisplayListItems = new ArrayList<>();

    private List<DisplayListItem> mManagerDisplayListItems = new ArrayList<>();

    @Override
    public void loadCartAddressList(String tag, final OnAccessNetListener<List<DisplayListItem>> listener) {
        BaseRequest request = new BaseRequest();
        request.setUrl(Urls.GET_CART_ADDRESS);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setTag(tag);

        mNetBiz.sendGetRequest(request, QueryUserAddressListResponse.class, new NetListener<QueryUserAddressListResponse>() {
            @Override
            public void onSuccess(QueryUserAddressListResponse response) {
                mChooseDisplayListItems.clear();

                QueryUserAddressListResponse.Data data = response.getData();

                // 地址列表
                List<UserAddress> userAddressList = data.getAddressList();

                // 重置用户UserAddressManager 中地址列表
//                UserAddressManager.getInstance().initAddressList(userAddressList);

                // 默认选择的地址
                final String defaultAddressId = data.getDefaultAddress();

                // 转换成 选择的ListItem
                List<DisplayListItem> addressListItems = Functional.serverToClient(userAddressList, new Functional.Processor<UserAddress, DisplayListItem>() {
                    @Override
                    public DisplayListItem processToClient(UserAddress userAddress) {
                        // ** 选择地址列表中默认选中哪一个
////                                UserAddress savedUserAddress = UserAddressManager.getInstance().getSavedSelectedUserAddress();
//                                if (savedUserAddress == null) {
//                                    // 如果AddressManager中没有选中的地址（savedSelectedUserAddress），
//                                    // 也就是说没有在选择地址列表中切换过数据，则使用默认选择的地址
//                                    userAddress.setSelected(userAddress.getAddressId().equals(defaultAddressId));
//                                } else {
//                                    // 如果保存了选中的地址，且选中的地址在地址列表中存在
//                                    userAddress.setSelected(savedUserAddress.equals(userAddress));
//                                }

                        userAddress.setSelected(userAddress.getAddressId().equals(defaultAddressId));
                        return new ChooseAddressListItem(userAddress);
                    }
                });

                mChooseDisplayListItems.addAll(addressListItems);
                if (userAddressList.size() < 5) {
                    try {
                        List<Area> baseAddress = getCurrentBaseAddress(data.getAddressList().get(0));
                        // 最多只能显示5个地址 , 也就是 5个地址以内 显示 添加新地址选项
                        ChooseAddressAddListItem addressAddListItem = new ChooseAddressAddListItem(baseAddress);
                        mChooseDisplayListItems.add(addressAddListItem);
                    } catch (IndexOutOfBoundsException e) {
                        e.printStackTrace();
                    }
                }

                if (listener != null) {
                    listener.onSuccess(mChooseDisplayListItems);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void addUserAddress(String consignee, String mobile, int provinceId,
                               int cityId, int areaId, String address, String tag,
                               final OnAccessNetListener<Object> listener) {

        UpdateAddressRequest request = new UpdateAddressRequest();
        request.setUrl(Urls.ADD_USER_ADDRESS);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setTag(tag);
        request.setConsignee(consignee);
        request.setMobile(mobile);
        request.setProvinceId(provinceId);
        request.setCityId(cityId);
        request.setAreaId(areaId);
        request.setAddress(address);

        mNetBiz.sendPostRequest(request, BaseResponse.class, new NetListener<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                if (listener != null) {
                    listener.onSuccess(null);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void postRefreshAddressListEvent() {
        RefreshAddressListStateEvent event = new RefreshAddressListStateEvent();
        EventBus.getDefault().post(event);
    }

    @Override
    public void postRefreshAddressStateEvent() {
        EventBus.getDefault().post(new RefreshAddressListStateEvent());
    }

    @Override
    public void updateUserAddress(String consignee, String mobile, String addressId, int provinceId,
                                  int cityId, int areaId, String address, String tag,
                                  final OnAccessNetListener<Object> listener) {

        UpdateAddressRequest request = new UpdateAddressRequest();
        request.setUrl(Urls.UPDATE_USER_ADDRESS);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setAddressId(addressId);
        request.setConsignee(consignee);
        request.setMobile(mobile);
        request.setProvinceId(provinceId);
        request.setCityId(cityId);
        request.setAreaId(areaId);
        request.setAddress(address);

        mNetBiz.sendPostRequest(request, BaseResponse.class, new NetListener<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                if (listener != null) {
                    listener.onSuccess(null);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void setDefaultAddress(
            String addressId, String tag, final OnAccessNetListener<Object> listener) {

        SetDefaultAddressRequest request = new SetDefaultAddressRequest();
        request.setAddressId(addressId);
        request.setUrl(Urls.SET_DEFAULT_ADDRESS);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));

        mNetBiz.sendGetRequest(request, BaseResponse.class, new NetListener<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                if (listener != null) {
                    listener.onSuccess(null);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void loadUserAddressListWhenManager(
            String tag, final OnAccessNetListener<List<DisplayListItem>> listener) {

        BaseRequest request = new BaseRequest();
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setUrl(Urls.USER_ADDRESS_LIST);

        mNetBiz.sendGetRequest(request, QueryUserAddressListResponse.class, new NetListener<QueryUserAddressListResponse>() {
            @Override
            public void onSuccess(QueryUserAddressListResponse response) {
                mManagerDisplayListItems.clear();

                QueryUserAddressListResponse.Data data = response.getData();

                // 地址列表
                List<UserAddress> userAddressList = data.getAddressList();

                // 对地址进行管理（添加和删除）后，重置用户UserAddressManager 中地址列表
                UserAddressManager.getInstance().initAddressList(userAddressList);

                // 默认选择的地址
                final String defaultAddressId = data.getDefaultAddress();

                // 转换成 管理的ListItem
                List<DisplayListItem> managerListItems = Functional.serverToClient(userAddressList,
                        new Functional.Processor<UserAddress, DisplayListItem>() {
                            @Override
                            public DisplayListItem processToClient(UserAddress userAddress) {
                                if (!TextUtils.isEmpty(defaultAddressId) && defaultAddressId.equals(userAddress.getAddressId())) {
                                    userAddress.setDefault(true);
                                } else {
                                    userAddress.setDefault(false);
                                }
                                return new AddressManagerListItem(userAddress);
                            }
                        });

                mManagerDisplayListItems.addAll(managerListItems);

                if (userAddressList.size() < 5) {
                    try {
                        List<Area> baseAddress = getCurrentBaseAddress(data.getAddressList().get(0));
                        AddAddressListItem addressAddListItem = new AddAddressListItem(baseAddress);
                        // 最多只能显示5个地址 , 也就是 5个地址以内 显示 添加新地址选项
                        mManagerDisplayListItems.add(addressAddListItem);
                    } catch (IndexOutOfBoundsException e) {
                        e.printStackTrace();
                    }
                }

                if (listener != null) {
                    listener.onSuccess(mManagerDisplayListItems);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @NonNull
    private List<Area> getCurrentBaseAddress(UserAddress userAddress) {
        String province = userAddress.getProvince();
        String provinceId = userAddress.getProvinceId();

        // 省
        Area provinceObj = new Area();
        provinceObj.setRegionName(province);
        provinceObj.setRegionId(Integer.parseInt(provinceId));

        String city = userAddress.getCity();
        String cityId = userAddress.getCityId();

        // 市
        Area cityObj = new Area();
        cityObj.setRegionName(city);
        cityObj.setRegionId(Integer.parseInt(cityId));

        String district = userAddress.getDistrict();
        String districtId = userAddress.getAreaId();

        // 区、县
        Area districtObj = new Area();
        districtObj.setRegionName(district);
        districtObj.setRegionId(Integer.parseInt(districtId));

        List<Area> areas = new ArrayList<Area>();
        areas.add(provinceObj);
        areas.add(cityObj);
        areas.add(districtObj);
        return areas;
    }

    @Override
    public void deleteUserAddress(
            String addressId, String tag, final OnAccessNetListener<Object> listener) {

        DeleteUserAddressRequest request = new DeleteUserAddressRequest();
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setUrl(Urls.DELETE_ADDRESS);
        request.setAddressId(addressId);

        mNetBiz.sendGetRequest(request, BaseResponse.class, new NetListener<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                if (listener != null) {
                    listener.onSuccess(null);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void getAddressChangeHost(String tag, String city, final OnAccessNetListener<String> listener) {
        AddressRequest request = new AddressRequest();
        request.setTag(tag);
        request.setUrl(Urls.LOCATION_DOMAIN);
        request.setCity(city);
        mNetBiz.sendGetRequest(request, AddressResponse.class, new NetListener<AddressResponse>() {
            @Override
            public void onSuccess(AddressResponse addressResponse) {
                AddressResponse.DataBean data = addressResponse.getData();
                if (null != data) {
                    String domain = data.getDomain();
                    if (!TextUtils.isEmpty(domain)) {
                        if (listener != null) {
                            listener.onSuccess(domain);
                        }
                    }
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return false;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void getAreaList(String regionId, String tag, final OnAddressListener listener) {

        QueryAreaRequest request = new QueryAreaRequest();
        request.setUrl(Urls.GET_AREA_LIST);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setTag(tag);
        request.setRegionId(regionId);

        mNetBiz.sendGetRequest(request, QueryAreaResponse.class, new NetListener<QueryAreaResponse>() {
            @Override
            public void onSuccess(QueryAreaResponse response) {
                List<Area> areaList = response.getAreaList();
                if (listener != null) {
                    listener.onSuccess(areaList);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    @Override
    public void changeAddress(String tag, String addressId, final OnAccessNetListener<Object> listener) {

        ChangeAddressRequest request = new ChangeAddressRequest();
        request.setUrl(Urls.CHANGE_ADDRESS);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setAddressId(addressId);

        mNetBiz.sendPostRequest(request, BaseResponse.class, new NetListener<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                if (listener != null) {
                    listener.onSuccess(null);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {

            }
        });


    }
}
